#!/bin/bash

BUILD_ROOT=build

# 定义 usage 函数，用于打印脚本的使用方法
function usage() {
    echo "Usage: $0 <architecture> <build_type>"
    echo "Architecture: x86_64 or aarch64"
    echo "Build type: Debug or Release"
}

# 如果参数个数小于 1，则打印使用方法并退出
if [[ $# -lt 1 ]]; then
    usage
    exit 1
fi

# 定义 build_mode 函数，用于根据传入的参数设置构建类型
function build_mode() {
    if [[ "$1" == *[Dd][Ee][Bb][Uu][Gg] ]]; then
        echo "Debug"
    elif [[ "$1" == *[Rr][Ee][Ll][Ee][Aa][Ss][Ee] ]]; then
        echo "Release"
    else
        echo "Debug"
    fi
}

# 定义 build 函数，用于构建指定架构和构建类型的目标
function build() {
    # 如果架构是 x86_64，则设置 CC、CXX、BUILD_DIR 和 Architecture 等环境变量
    if [[ "$1" == *[xX][8][6]* ]]; then
        export CC=/usr/bin/clang
        export CXX=/usr/bin/clang++
        export BUILD_DIR=./$BUILD_ROOT/build_x86_64
        export Architecture=x86_64
        echo "Building for x86_64"
    # 如果架构是 aarch64，则设置 CC、CXX、BUILD_DIR 和 Architecture 等环境变量
    elif [[ "$1" == *[aA][aA][rR][cC][hH][6][4]* ]]; then
        # export CC=/usr/bin/aarch64-linux-gnu-gcc
        # export CXX=/usr/bin/aarch64-linux-gnu-g++
        export CC=/opt/tools/cgtools/gcc-arm-9.2-2019.12-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc
        export CXX=/opt/tools/cgtools/gcc-arm-9.2-2019.12-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-g++
        export BUILD_DIR=./$BUILD_ROOT/build_aarch64
        export Architecture=aarch64
        echo "Building for aarch64"
    # 如果架构不是 x86_64 或 aarch64，则打印错误信息并退出
    else
        echo "Unsupported architecture: $1"
        exit 1
    fi

    # 根据传入的参数设置构建类型
    export BUILD_TYPE=$(build_mode "$2")
    echo "Building in $BUILD_TYPE mode"

    # 删除 BUILD_DIR 目录并重新创建
    mkdir -p ./$BUILD_DIR
    mkdir -p ./$DIST_ROOT

    # 使用 CMake 生成 Makefile 并构建目标
    cmake --no-warn-unused-cli -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_BUILD_TYPE:STRING= $BUILD_TYPE -DCMAKE_C_COMPILER:FILEPATH=$CC -DCMAKE_CXX_COMPILER:FILEPATH=$CXX -S. -B$BUILD_DIR -G "Unix Makefiles"
    cmake --build $BUILD_DIR --config $BUILD_TYPE --target all -- -j 32
    cmake --build $BUILD_DIR --target install
}

# 定义 clean 函数，用于清理所有目标
function clean() {
    rm -rf $BUILD_ROOT
    rm -rf $DIST_ROOT
    echo "Cleaned all targets"
}

# 如果第一个参数是 "clean"，则清理所有目标
if [[ "$1" == "clean" ]]; then
    clean
# 如果第一个参数是 "all"，则构建 x86_64 和 aarch64 两种架构的目标
elif [[ "$1" == "all" ]]; then
    build "x86_64" $2
    build "aarch64" $2
# 否则，构建指定架构和构建类型的目标
else
    build $1 $2
fi